package com.example.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.reggie.common.deploy.R;
import com.example.reggie.common.table.MsgTable;
import com.example.reggie.entity.User;
import com.example.reggie.service.UserService;
import com.example.reggie.utils.EmailSMSUtils;
import com.example.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private EmailSMSUtils emailSMSUtils;

    private String fromEmail="2114568838@qq.com";
    private String delegationCode="zsokmnfsdrblbhec";
    /**
     * 发送消息
     *
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        String email = user.getPhone();
        if (!StringUtils.isEmpty(email)) {
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            emailSMSUtils.sendMail(email,fromEmail,delegationCode,code);
            log.info(code);
            session.setAttribute(email,code);
        } else {
            R.error(MsgTable.SEND_MESSAGE_ERR);
        }
        return R.success(MsgTable.SEND_MESSAGE_OK);
    }

    //TODO 返回值类型很奇怪
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        String email = map.get("phone").toString();
        String code = map.get("code").toString();
        String real_code = session.getAttribute(email).toString();
        if(real_code!=null&&real_code.equals(code)){
            LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,email);
            User one = userService.getOne(queryWrapper);
            if(one==null){
                one=new User();
                one.setPhone(email);
                one.setStatus(1);
                userService.save(one);
            }
            session.setAttribute("user",one.getId());
            return R.success(one);
        }
        return R.error(MsgTable.LOGIN_ERR);
    }
}
